package base.thread_JUC.demo04;

import lombok.Getter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/** MYNOTICE
 * JUC: CountDownLatch 的使用
 * 给定一个计数，每调一次接口-1，直至减为0，才去触发被阻塞的线程
 */
public class Client1 {
    public static void main(String[] args) {
//        testCase1();
        testCase2();
    }


    public static void testCase1(){
        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(()->{
                try {
                    TimeUnit.SECONDS.sleep(1);// 模拟整理工作中...
                    System.out.println(Thread.currentThread().getName()+"\t 整理工作完毕，下班回家");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, String.valueOf(i)).start();
        }

        try {
            /**
             * MYWHAT
             * main 线程是如何感知到其他线程对 CountDownLatch 的改变的？
             */
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t 下班最后锁门走人");
    }

    // 枚举的高级用法
    public static void testCase2(){
        CountDownLatch latch = new CountDownLatch(6);

        for (int i = 1; i <=latch.getCount() ; i++) {
            new Thread(()->{
                try {
                    TimeUnit.SECONDS.sleep(1);//模拟被灭的经过时间
                    System.out.println(Thread.currentThread().getName()+"\t 被灭");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, CountryEnum.getCountry(i).getCountryName()).start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"\t 最终秦国统一六国");
    }
}

enum CountryEnum {
    ONE(1,"齐国"), TWO(2,"楚国"), THREE(3,"燕国"),
    FOUR(4,"韩国"), FIVE(5,"赵国"), SIX(6,"魏国");

    @Getter
    private Integer retCode;
    @Getter
    private String  countryName;

    CountryEnum(Integer retCode, String countryName){
        this.retCode = retCode;
        this.countryName = countryName;
    }

    public static CountryEnum getCountry(int index){
        CountryEnum[] country = CountryEnum.values();
        for (CountryEnum ce : country) {
            if (ce.getRetCode()==index) {
                return ce;
            }
        }
        return null;
    }

}


